'use strict';
var domain 	= require('domain');
var express = require('express');
var path 		= require('path');
var bodyParser 		= require('body-parser');
var AV 						= require('leanengine');

var http	= require('http');
var ejs 	= require('ejs');




//自定义函数及控制器
var cMain		= require('./controllers/main');
var cAdmin	= require('./controllers/admin');
var cAdminNews		= require('./controllers/admin_news');





var app 		= express(),
	  admin		= express();

// 设置 view 引擎

app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');

// 设置模板目录
admin.set('views',path.join(__dirname, 'views/admin'));   // 设置模板目录
app.use(express.static('public'));

app.use(AV.express());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// 未处理异常捕获 middleware
app.use((req, res, next) => {
  let d = domain.create();
  d.add(req);
  d.add(res);
  d.on('error', (err) => {
    console.error('uncaughtException url=%s, msg=%s', req.url, err.stack || err.message || err);
    if (!res.finished) {
      res.statusCode = 500;
      res.setHeader('content-type', 'application/json; charset=UTF-8');
      res.end('uncaughtException');
    }
  });
  d.run(next);
});

app.use(AV.Cloud.CookieSession({secret: 'youzhan', maxAge: 3600000,fetchUser:true}));

app.get('/', cMain.homePage);//网站首页

/*
后台管理
*/
app.get('/admin-login', cAdmin.loginPage);	//登录页面
app.post('/admin-login', cAdmin.doLogin);	//登录帐号
app.get('/admin-logout',cAdmin.doLogout);	//登出帐号


app.use('/admin', admin);
admin.use(cAdmin.doCkAuth);

admin.get('/index', cAdmin.indexPage);
admin.get('/news/detail', cAdminNews.detailPage);
admin.get('/news/detail2', cAdminNews.validPage);
admin.post('/news/save', cAdminNews.doSave);


// 如果任何路由都没匹配到，则认为 404
// 生成一个异常让后面的 err handler 捕获
app.use(function(req, res, next) {
  res.status(404).render('404.html', {title: 'Sorry, page not found'});
});

// 如果是开发环境，则将异常堆栈输出到页面，方便开发调试
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) { // jshint ignore:line
    var statusCode = err.status || 500;
    if(statusCode === 500) {
      console.error(err.stack || err);
    }
    res.status(statusCode);
    res.render('error', {
      message: err.message || err,
      error: err
    });
  });
}

// 如果是非开发环境，则页面只输出简单的错误信息
app.use(function(err, req, res, next) { // jshint ignore:line
  res.status(err.status || 500);
  res.render('error', {
    message: err.message || err,
    error: {}
  });
});

module.exports = app;
